<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="UTF-8"%>
<%!
Color getRandColor(int fc, int bc) {//给定范围获得随机颜色
	Random random = new Random();
	if (fc > 255)
		fc = 255;
	if (bc > 255)
		bc = 255;
	int r = fc + random.nextInt(bc - fc);
	int g = fc + random.nextInt(bc - fc);
	int b = fc + random.nextInt(bc - fc);
	return new Color(r, g, b);
}
%>
<%
	out.clear();
	//设置页面不缓存
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);
	//创建随机类
	Random r = new Random();
	/* char[] codeSequence = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
			's','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N',
			'O','P','Q', 'R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};*/ 
	char[] codeSequence = {'0','1','2','3','4','5','6','7','8','9'};
	//在内存中创建图像，宽度为width， 高度为height
	int width = 60;
	int height = 20;
	BufferedImage pic = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	//获取图形上下文环境
	Graphics gc = pic.getGraphics();
	//设定背景色并填充
	gc.setColor(getRandColor(200, 250));
	gc.fillRect(0, 0, width, height);
	//设定图形上下文字体
	gc.setFont(new Font("Arial", Font.PLAIN, 18));
	//随机产生200条干扰直线
	gc.setColor(getRandColor(160, 200));
	for (int i = 0; i < 200; ++i) {
		int x1 = r.nextInt(width);
		int y1 = r.nextInt(height);
		int x2 = r.nextInt(15);
		int y2 = r.nextInt(15);
		gc.drawLine(x1, y1, x1 + x2, y1 + y2);
	}
	//随机产生100个干扰点
	gc.setColor(getRandColor(120, 240));
	for (int i = 0; i < 100; ++i) {
		int x = r.nextInt(width);
		int y = r.nextInt(height);
		gc.drawOval(x, y, 0, 0);
	}
	//随机产生4位数字的验证码
	String rand = "";
	String code = "";
	for (int i = 0; i < 4; ++i) {
		code = String.valueOf(codeSequence[(int) (codeSequence.length * Math.random())]);
		rand += code;
		gc.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110), 20 + r.nextInt(110)));
		gc.drawString(code, (15 * i) + 3, 16);
	}
	//释放图形上下文环境
	gc.dispose();
	//将认证码RS存入session
	String captchaImgId = request.getParameter("imageId");
	// 将认证码存入SESSION
	session.setAttribute(captchaImgId, rand);
	//输出生成的验证码图像
	ImageIO.write(pic, "jpeg", response.getOutputStream());
%>